<script lang="ts" setup>
import type {Chapter} from '@/types/request';
import {message} from 'ant-design-vue';

defineProps<{
    current: number
    chapters: Chapter[]
}>()
// 修改父组件数据
const emits = defineEmits<{
    (e: 'update:current', value: number): void
    (e: 'update:chapters', value: Chapter[]): void
}>()

// 子组件章集初始数据
const chapters = $ref<Chapter[]>([]);


/**
 * 章处理的逻辑
 */
// 创建初始章
function createChapter() {
    chapters.push({
        title: '请修改为自己的标题',
        ordered: chapters.length,
        episodeList: [],
    });
}

// 初始创建第一章
createChapter();

// 编辑章标题
function editChapterTitle(index: number, value: string) {
    chapters[index].title = value;
}

// 删除章
function delChapter(index: number) {
    if (index === 0) {
        message.warn('不可删除第一章节');
        return;
    }
    chapters.splice(index, 1);
}


/**
 * 集处理逻辑
 */
// 创建集
function createEpisode(chapterIndex: number) {
    chapters[chapterIndex].episodeList.push({
        chapterId: chapterIndex,
        title: '请修改为自己的标题',
        ordered: chapters[chapterIndex].episodeList.length,
    });
}

// 编辑集标题
function editEpisodeTitle(
        chapterIndex: number,
        index: number,
        value: string
) {
    chapters[chapterIndex].episodeList[index].title = value;
}

// 删除集
function delEpisode(chapterIndex: number, index: number) {
    chapters[chapterIndex].episodeList.splice(index, 1);
}


// 上一步按钮
function handlePrev() {
    emits('update:current', 0)
}

// 下一步按钮
function handleNext() {
    if (chapters[0].episodeList.length === 0) {
        message.warn('请至少填写一个以上的集数')
        return
    }
    emits('update:current', 2)
    emits('update:chapters', chapters)
}
</script>

<template>
    <div>
        <div ml-auto flex justify-end>
            <a-button type="primary" mb @click="createChapter()">新增章</a-button>
        </div>
        <Chapter v-for="(chapter, idx) in chapters" :key="idx" :index="chapter.ordered" :title="chapter.title"
                 :expand-init="idx < 3" @edit-chapter="editChapterTitle" @add-episode="createEpisode"
                 @del-chapter="delChapter" mb>
            <Episode v-for="(episode, subIdx) in chapter.episodeList" :key="subIdx" :index="subIdx"
                     :title="episode.title"
                     :chapter-index="idx" @del-episode="delEpisode" @edit-episode="editEpisodeTitle"/>
        </Chapter>
        <div flex justify-end gap-2 mt-8>
            <a-button @click="handlePrev">上一步</a-button>
            <a-button type="primary" @click="handleNext">下一步</a-button>
        </div>
    </div>
</template>
